﻿#region Copyright Information
// // ****************************************************************
// // Feel free to extend or modify the code of the application to your needs. 
// // But remember do it for the Glory of our Lord Jesus Christ
// // ****************************************************************
#endregion

#region Usings

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Data;
using Interfaces.Persistence;
using NLog;
using Persistence.Properties;

#endregion

namespace Persistence
{
    /// <summary>
    /// Description of MyClass.
    /// </summary>
    public class PersistenceManager : IPersistanceManager
    {
        /// <summary>
        /// Reference to logging tool.
        /// </summary>
        private static readonly Logger logging = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// Holds all songs.
        /// </summary>
        private readonly List<SongInfo> allSongs;

        /// <summary>
        /// Holds the songs file.
        /// </summary>
        private readonly XDocument songsElements;

        /// <summary>
        /// <see cref="PersistenceManager"/> constructor.
        /// </summary>
        /// <param name="configurationPath">The path to the songs file.</param>
        public PersistenceManager(string configurationPath)
        {
            // Load the configuration file.
            songsElements = XDocument.Load(configurationPath);
            // Populate the list of songs.
            allSongs = (from songs in songsElements.Root.Elements().AsParallel()
                        select
                            // Build the SongInfo List.
                            new SongInfo(
                            Guid.Parse(songs.Attribute(Settings.Default.Id).Value),
                            songs.Attribute(Settings.Default.Name).Value,
                            from lyrics in songs.Elements()
                            select
                                // Build the LyricsInfo List.
                                new LyricInfo(
                                // Number of verse.
                                int.Parse(lyrics.Attribute(Settings.Default.Number).Value),
                                // List of verse.
                                from verse in lyrics.Elements()
                                select verse.Attribute(Settings.Default.Text).Value,
                                // Type of verse.
                                (VerseType)
                                Enum.Parse(typeof (VerseType), lyrics.Attribute(Settings.Default.Type).Value, true)))).
                ToList();

            logging.Info("Loading the songs from the configuration file.");
        }

        #region IPersistanceManager Members

        /// <summary>
        /// Returns all the <see cref="SongInfo"/> in the Persistence.
        /// </summary>
        /// <returns><code>List[SongInfo]</code></returns>
        public IEnumerable<SongInfo> GetAll()
        {
            logging.Info("Retrieving the songs.");
            return allSongs.OrderBy(song => song.Name);
        }

        /// <summary>
        /// Returns a song by its name.
        /// </summary>
        /// <param name="name">The name of the song.</param>
        /// <returns>All the information associated with a song.</returns>
        public SongInfo GetSongByName(string name)
        {
            logging.Info("Return a song by its name.");
            return allSongs.First(songName => songName.Name == name);
        }

        /// <summary>
        /// Add a Song to the Persistence.
        /// </summary>
        /// <param name="song">Song name.</param>
        public void AddSong(SongInfo song)
        {
            allSongs.Add(song);
            logging.Info("Add a new song.");
        }

        /// <summary>
        /// Removes a song from the Persistence.
        /// </summary>
        /// <param name="song">Song name.</param>
        public void RemoveSong(string song)
        {
            allSongs.RemoveAll(songName => songName.Name == song);
            logging.Info("Remove the specified song.");
        }

        /// <summary>
        /// Updates a song.
        /// </summary>
        /// <param name="song">The song to pe updated.</param>
        public void UpdateSong(SongInfo song)
        {
            allSongs.RemoveAll(songName => songName.Name == song.Name);
            allSongs.Add(song);
            logging.Info("Update the specified song.");
        }

        /// <summary>
        /// Save the configuration file.
        /// </summary>
        /// <param name="configurationPath">The location to save the file.</param>
        /// <param name="songs">The list of songs to be saved.</param>
        public void Save(string @configurationPath, IEnumerable<SongInfo> songs)
        {
            foreach (SongInfo song in songs)
            {
                // Iterate through the songs and remove from the file the ones in the list.
                songsElements.Root.Elements().Where(id => Guid.Parse(id.Attribute(Settings.Default.Id).Value) == song.Id)
                    .Remove();

                // Create a song element.
                var newSong = new XElement(Settings.Default.Song);

                // Add its (generate) id and its name.
                newSong.SetAttributeValue(Settings.Default.Id, Guid.NewGuid());
                newSong.SetAttributeValue(Settings.Default.Name, song.Name);

                // Iterate all lyrics.
                foreach (LyricInfo lyric in song.Lyrics)
                {
                    // Create a lyrics element.
                    var lyrics = new XElement(Settings.Default.Lyrics);

                    // Add its number.
                    lyrics.SetAttributeValue(Settings.Default.Number, lyric.Number);

                    // Add its type.
                    lyrics.SetAttributeValue(Settings.Default.Type, lyric.Type);

                    // Iterate through the verses and add them to the lyrics structure.
                    foreach (string verse in lyric.Verse)
                    {
                        var verseElement = new XElement(Settings.Default.Verse, verse);
                        lyrics.Add(verseElement);
                    }
                    // Add the lyrics to the song.
                    newSong.Add(lyrics);
                }
                // Add the song to the songs xml.
                songsElements.Root.Add(newSong);
            }

            // Save the file to disk.
            try
            {
                songsElements.Save(@configurationPath);
                logging.Info("Save songs to file.");
            }
            catch (IOException ioException)
            {
                logging.Error("Error " + ioException.Message);
            }
        }

        #endregion
    }
}